/*
 * @Author: 9ilk 3535851673@qq.com
 * @Date: 2025-02-07 13:58:44
 * @LastEditors: 9ilk 3535851673@qq.com
 * @LastEditTime: 2025-02-07 17:48:29
 * @FilePath: /zhuang/thirdpath/MySQLConnect/test.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include<iostream>
#include<mysql/mysql.h>
#include<unistd.h>
#include<string>
using namespace std;

const string host = "127.0.0.1";
const string user = "connector";
const string passwd = "zhuang11";
const string db = "conn";
const unsigned int port = 3306;

int main()
{
//   cout << mysql_get_client_info() << endl;
  MYSQL* my = mysql_init(nullptr);
  if(my == nullptr)
  {
    cerr << "init MySQL error" << endl;
    return 1;
  }
  //连接
  if(mysql_real_connect(my,host.c_str(),user.c_str(),passwd.c_str(),db.c_str(),port,nullptr,0) == nullptr)
  {
      //连接失败
      cerr << "connect  MySQL error" << endl;
      return 2;
  }
  mysql_set_character_set(my,"utf8");
//   sleep(10);
  cout << "connect success " << endl;
  //下达指令
  string sql = "select * from user";
  int n = mysql_query(my,sql.c_str());
  if(n == 0) cout << sql <<" success: " << n << endl;
  else 
  {
     cerr << "failed: " << n << endl;
     return 3;
  }
  MYSQL_RES * res = mysql_store_result(my);
  if(res == nullptr)
  {
     cerr << "mysql_store_reasult error" << endl;
     return 4;
  }
  int rows = mysql_num_rows(res); //行数
  int fields = mysql_num_fields(res); //列数
  //表属性
  MYSQL_FIELD* fieldarray =  mysql_fetch_fields(res); 
  for(int i = 0 ; i < fields;i++)
  {
     cout << fieldarray[i].name << "\t";//列名
  }
  cout << "\n";

  //表内容
  for(int i = 0 ; i < rows ; i++)
  {
    MYSQL_ROW row = mysql_fetch_row(res); //char** 一行结果  
    for(int j = 0 ; j < fields;j++)
    {
         cout << row[j] << "\t"; // *(row+j)
    }
    cout << "\n";
  }

  cout << fieldarray[0].db << " " <<  fieldarray[0].table <<endl;

//   string sql;
//   while(true)
//   {
//      cout << "MySQL >>";
//      if(!getline(cin,sql) || sql == "quit") 
//      {
//         cout << "Bye"<< endl;
//         break;
//      }
//      int n = mysql_query(my,sql.c_str());
//      if(n == 0) cout << sql <<" success: " << n << endl;
//      else cerr << "failed: " << n << endl;
//   }
  mysql_free_result(res); //释放结果集否则内存泄露
  mysql_close(my);
  return 0;
}






